import axios, { type Method } from 'axios';
import { type UserInfo } from './AccountStore';
import { useAccountStore } from './AccountStore';

// 定义接口路径
enum RequestPath {
    login = '/users/login',
    signup = 'users/signup',
    operationalAdd = '/operational/add',
    operationalGet = '/operational/get',
    operationalUpdate = '/operational/update',
    goodsCategoryGet = '/goods/category/get',
    goodsCategoryAdd = '/goods/category/add',
    goodsCategoryUpdate = '/goods/category/update',
    goodsGet = '/goods/get',
    goodsListGet = '/goods/list/get',
    goodsListSearch = '/goods/list/search',
    goodsAdd = '/goods/add',
    goodsUpdate = '/goods/update',
    goodsDelete = '/goods/delete',
}
// 创建一个请求worker实例
const worker = axios.create({
    baseURL: 'http://localhost:3000/api/v1',
    timeout: 5000,
    headers: {}
});
// 登录和注册接口数据的返回结构
export interface LoginResponseData {
    msg: 'error' | 'ok',
    error?: string,
    info: UserInfo,
    token?: string,
}
export interface OperationalItemData {
    id: number;
    name: string;
    status: number;
    created_at: string;
    cover: string;
    content: string;
    uri: string;
}
export interface OperationalResponseData {
    msg: 'error' | 'ok';
    error?: string;
    datas?: OperationalItemData[];
}
// 发起请求的方法
function startRequest(path: RequestPath, method: Method, params: any) {
    let config: Record<string, any> = {
        method,
        url: path,
    }
    // get方法将参数放在params中
    if (['get', 'GET'].includes(method)) {
        config.params = params;
    // post方法将参数放在data中
    } else {
        config.data = params;
    }
    // 会返回一个promise
    return worker.request(config);
}

// 定义一个拦截器
worker.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (error.response.status == 401) {
        // 直接退出登录
        useAccountStore().logout();
        window.location.href = '/#/login';
    }
    return Promise.reject(error);
})

export {
    worker,
    RequestPath,
    startRequest,
}